package org.springblade.modules.admin.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.modules.admin.dto.FeedbackRequest;
import org.springblade.modules.admin.entity.FeedbackReasons;
import org.springblade.modules.admin.mapper.FeedbackReasonsMapper;
import org.springblade.modules.admin.service.FeedbackReasonsService;
import org.springblade.modules.admin.vo.FeedbackResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Service
public class FeedbackReasonsServiceImpl extends BaseServiceImpl<FeedbackReasonsMapper, FeedbackReasons> implements FeedbackReasonsService {

	@Value("${dify.api.url}")
	private String difyApiUrl;

	@Value("${dify.api.key}")
	private String apiKey;

	@Override
	public FeedbackResponse postFeedbackReasons(FeedbackRequest feedbackRequest, String messageId) {
		// 构建URL
		String url = difyApiUrl + "/v1/messages/" + messageId + "/feedbacks";

		// 构建请求体
		HashMap<String, Object> paramMap = new HashMap<>();
		paramMap.put("user", AuthUtil.getUserId().toString());
		paramMap.put("rating", "null".equals(feedbackRequest.getRating()) ? null : feedbackRequest.getRating());

		ObjectMapper mapper = new ObjectMapper();
		mapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);

		String requestBody = null;
		try {
			requestBody = mapper.writeValueAsString(paramMap);
		} catch (JsonProcessingException e) {
			throw new RuntimeException(e);
		}
		System.out.println(requestBody);
		// 使用Hutool发送请求
		String result = HttpRequest.post(url)
			.header("Content-Type", "application/json")
			.header("Authorization", "Bearer " + apiKey)
			.body(requestBody.toString())
			.execute()
			.body();

		// 解析响应
		FeedbackResponse response = JSONUtil.toBean(result, FeedbackResponse.class);
		return response;
	}
}
